package com.lx.boot1;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lx.boot.cache.codec.SerializedObjectCodec;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;

@Component
public class MySerializedObjectCodec extends SerializedObjectCodec {

    private final ObjectMapper objectMapper = new ObjectMapper()
            .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); // 启用类型信息

    @Override
    public Object decodeValue(ByteBuffer bytes) {
        try {
            byte[] array = new byte[bytes.remaining()];
            bytes.get(array);
            return objectMapper.readValue(array, Object.class);
        } catch (Exception e) {
            throw new SerializationException("Could not decode value", e);
        }
    }

    @Override
    public ByteBuffer encodeValue(Object value) {
        try {
            byte[] bytes = objectMapper.writeValueAsBytes(value);
            return ByteBuffer.wrap(bytes);
        } catch (Exception e) {
            throw new SerializationException("Could not encode value", e);
        }
    }
}
